// pages/print/print.js
// api
const $api = require('../../utils/request.js').Api;
//打印
Page({
  /**
   * 页面的初始数据
   */
  data: {
    time: "",
    phoneNum: "",//手机号
    content: "",//预报价金额
    popup: "",//预报价弹窗
    number: 1,//数量输入框
    disabled1: true,//数量最小值
    bindNum: 0,//装订本数输入框
    disabled2: false,//装订本数最小值
    bindNumShow: true,//装订本数是否显示
    // 文本域
    minAddr: 0,
    maxAddr: 100,
    //打印业务
    colorList: require('../../utils/staticData.js').colorList,//颜色
    sizeList: require('../../utils/staticData.js').sizeList,//尺寸
    printTypeList: require('../../utils/staticData.js').printTypeList,//打印类型
    printPaperTypeList: require('../../utils/staticData.js').printPaperTypeHbList,//纸张类型
    bindTypeList: require('../../utils/staticData.js').bindTypeList,//装订方式
    //页面参数
    formData: {
      openId: "",//小程序唯一ID
      wxName: "",//姓名
      wxPhone: "",//电话
      wxCompany: "",//单位
      bizType: "10",//业务
      //打印业务
      printColor: "",//颜色
      size: "",//尺寸
      printType: "",//打印类型
      printPaperType: "",//纸张类型
      num: "",//数量
      bindType: "",//装订方式
      bindNum: "",//装订本数
      otherDemand: "",//其他需求
      expectDate: "",//期望时间
      prePrice: ""//预估价
    },
    rules: [{
      name: 'wxName',
      rules: { required: true, message: '请输入姓名' },
    }, {
      name: 'wxPhone',
      rules: [{ required: true, message: '请输入电话' },
      { mobile: true, message: '手机号格式不对' }]
    }, {
      name: 'wxCompany',
      rules: { required: true, message: '请输入单位' },
    }, {
      name: 'otherDemand',
      rules: { required: true, message: '请输入其他需求' },
    }]
  },
  //页面跳转首页
  onTapJumIndex() {
    wx.redirectTo({
      url: '/pages/index/index',
    })
  },
  //取消返回首页
  cancelForm() {
    wx.redirectTo({
      url: '/pages/index/index',
    })
  },
  //页数加减
  prevNum() {
    this.setData({
      number: Number(this.data.number) + 1,
      disabled1: Number(this.data.number) + 1 > 1 ? false : true,
    });
  },
  nextNum() {
    this.setData({
      number: Number(this.data.number) <= 0 ? 0 : Number(this.data.number) - 1,
      disabled1: Number(this.data.number) - 1 > 1 ? false : true,
    });
  },
  //装订本数加减
  prevBindNum() {
    this.setData({
      bindNum: Number(this.data.bindNum) + 1,
      disabled2: Number(this.data.bindNum) !== 0 ? false : true,
    });
  },
  nextBindNum() {
    this.setData({
      bindNum: Number(this.data.bindNum) <= 0 ? 0 : Number(this.data.bindNum) - 1,
      disabled2: Number(this.data.bindNum) !== 0 ? false : true,
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let date = new Date();
    // 时区补偿
    date.setMinutes(date.getMinutes() - date.getTimezoneOffset());
    //赋值默认值
    this.setData({
      //时间
      time: date.toJSON().substr(0, 10),
      //页面赋值
      [`formData.expectDate`]: date.toJSON().substr(0, 10),
      [`formData.printColor`]: (this.data.colorList)[0].value,
      [`formData.size`]: (this.data.sizeList)[1].value,
      [`formData.printType`]: (this.data.printTypeList)[0].value,
      [`formData.printPaperType`]: (this.data.printPaperTypeList)[0].value,
      [`formData.bindType`]: (this.data.bindTypeList)[0].value,
      //小程序唯一ID赋值
      [`formData.openId`]: wx.getStorageSync("openIdWy"),
      //手机号赋值
      phoneNum: wx.getStorageSync("phoneNum"),
      [`formData.wxPhone`]: wx.getStorageSync("phoneNum"),
    })
  },
  //颜色radio调用方法
  radioChangeColorList: function (e) {
    const items = this.data.colorList
    for (let i = 0, len = items.length; i < len; ++i) {
      items[i].checked = items[i].value === e.detail.value
    }
    //重新赋值
    this.setData({
      items,
      [`formData.printColor`]: e.detail.value
    })
    //如果用户点击彩色
    if ((e.detail.value) == 20) {
      this.setData({
        printPaperTypeList: require('../../utils/staticData.js').printPaperTypeCsList,//纸张类型
        [`formData.printPaperType`]: (this.data.printPaperTypeList)[0].value,
      })
    } else {
      this.setData({
        printPaperTypeList: require('../../utils/staticData.js').printPaperTypeHbList,//纸张类型
        [`formData.printPaperType`]: (this.data.printPaperTypeList)[0].value,
      })
    }
  },
  //尺寸radio调用方法
  radioChangeSizeList: function (e) {
    const items = this.data.sizeList
    for (let i = 0, len = items.length; i < len; ++i) {
      items[i].checked = items[i].value === e.detail.value
    }
    //重新赋值
    this.setData({
      items,
      [`formData.size`]: e.detail.value
    })
  },
  //打印类型radio调用方法
  radioChangePrintTypeList: function (e) {
    const items = this.data.printTypeList
    for (let i = 0, len = items.length; i < len; ++i) {
      items[i].checked = items[i].value === e.detail.value
    }
    //重新赋值
    this.setData({
      items,
      [`formData.printType`]: e.detail.value
    })
  },
  //纸张类型radio调用方法
  radioChangePrintPaperTypeList: function (e) {
    this.setData({
      [`formData.printPaperType`]: e.detail.value
    })
  },
  //装订方式radio调用方法
  radioChangeBindTypeList: function (e) {
    //隐藏装订本数
    if (e.detail.value == "40") {
      this.data.bindNumShow = true;
      this.data.bindNum = 0;//赋值为0
    } else {
      this.data.bindNumShow = false;
    }
    this.setData({
      bindNumShow: this.data.bindNumShow,
      bindNum: this.data.bindNum,
      [`formData.bindType`]: e.detail.value
    })
  },
  //期望时间
  bindDateChange(e) {
    this.setData({
      time: e.detail.value,
      [`formData.expectDate`]: e.detail.value
    })
  },
  //所有input框输入
  formInputChange(e) {
    const { field } = e.currentTarget.dataset
    this.setData({
      [`formData.${field}`]: e.detail.value
    })
  },
  //页数和装订本数输入框赋值
  formInputChangeNum(e) {
    const { field } = e.currentTarget.dataset
    var number = e.detail.value
    if (Number(e.detail.value) < 1) {
      number = 1
    }
    this.setData({
      [`${field}`]: number,
      number: number
    })
  },
  formInputChangeBindNum(e) {
    const { field } = e.currentTarget.dataset
    this.setData({
      [`${field}`]: e.detail.value
    })
  },
  // 其他需求判断
  inputeditAddr(e) {
    var value = e.detail.value;
    let dataset = e.currentTarget.dataset;
    this.data[dataset.obj] = value;
    var len = parseInt(value.length);
    if (len > this.data.maxAddr) return;
    this.setData({
      currentWordNumberAddr: len,
      [`formData.otherDemand`]: value
    });
    if (this.data.currentWordNumberAddr == 100) {
      wx.showModal({
        title: '提示',
        content: '您输入的次数已达上限',
      })
    }
  },
  //提交
  submitForm() {
    //把页数和装订本书赋值
    this.setData({
      [`formData.num`]: String(this.data.number),
      [`formData.bindNum`]: String(this.data.bindNum),
    })

    if ((this.data.formData).openId == null || (this.data.formData).openId == "") {//唯一ID为空返回首页重新登录
      wx.showToast({
        title: "请返回首页刷新",
        icon: 'error',
        duration: 3000
      })
      return
    }
    console.log(this.data.formData)
    //表单校验
    this.selectComponent('#form').validate((valid, errors) => {
      console.log('valid', valid, errors)
      //自定义校验页数和装订本数
      if (Number(this.data.number) <= 0) {
        this.setData({
          error: "页数请输入大于0的数值"
        })
        return
      }
      if ((this.data.formData.bindType) != "40") {
        if (Number(this.data.bindNum) <= 0) {
          this.setData({
            error: "装订本数请输入大于0的数值"
          })
          return
        }

      }
      if (!valid) {
        const firstError = Object.keys(errors)
        if (firstError.length) {
          this.setData({
            error: errors[firstError[0]].message
          })
        }
      } else {
        let popup = this.selectComponent("#popup");
        //调用预报价请求方法
        $api.calcPrePrice(this.data.formData).then((res) => {
          console.log(res.prePrice);
          this.setData({
            content: res.prePrice,
            [`formData.prePrice`]: res.prePrice
          });
          popup.showPopup();
        }).catch((error) => {
          console.log(error);
        });
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    //获得popup组件
    this.popup = this.selectComponent("#popup");
  },
  //取消事件
  _error() {
    console.log('你点击了取消');
    let popup = this.selectComponent("#popup");
    popup.hidePopup();
  },
  //确认事件
  _success() {
    //调用保存订单请求方法
    $api.createOrder(this.data.formData).then((res) => {
      //跳转至订单列表
      wx.switchTab({
        // url: '/pages/order/order?openId=' + this.data.formData.openId + '&orderId=' + res.orderId,
        url: '/pages/order/order?orderId=',
      })
    }).catch((error) => {
      console.log(error);
    });
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})